package net.huafv.authoritycontrol.admin.controller;


import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import net.huafv.authoritycontrol.common.lang.Const;
import net.huafv.authoritycontrol.common.lang.Result;
import net.huafv.authoritycontrol.utils.CaptchaUtil;
import net.huafv.authoritycontrol.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import javax.imageio.ImageIO;


@RestController
public class CaptchaController extends BaseController{

    @Autowired
    RedisUtil redisUtil;

    @GetMapping("/captcha")
    public Result getCaptcha(){
        String key = UUID.randomUUID().toString();
        String code = CaptchaUtil.generateCode();
        BufferedImage image = CaptchaUtil.generateImage(code);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, "jpg", outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        Base64.Encoder encoder = Base64.getEncoder();
        String str = "data:image/jpeg;base64,";


        String base64Img = str + encoder.encodeToString(outputStream.toByteArray());

        JSONObject data = JSONUtil.createObj()
                .putOpt("token", key)
                .putOpt("captchaImg", base64Img);

        redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);

        return Result.success(data);
    }

}
